<?php namespace App\Admin\Card\Recharge;

//基础条件
use App\Core\Repository\Criterias\FixedCriteria;
use App\Core\Repository\Criterias\PaginateCriteria;
use App\Core\Repository\Criterias\SortCriteria;
//过滤器
use App\Core\Repository\Criterias\Filters\InputCriteria;
use App\Core\Repository\Criterias\Filters\InputKeywordsCriteria;
use App\Core\Repository\Criterias\Filters\InputTimeRangeCriteria;

use Input;
use DB;
use App\Admin\User\User\Repository as UserRepository;

trait Service {
    
    //基础服务
    use \App\Core\Service\Service;
    use \App\Core\Service\Services\All;
    use \App\Core\Service\Services\Indexer;
    use \App\Core\Service\Services\Creater;
    use \App\Core\Service\Services\Updater;
    use \App\Core\Service\Services\Changer;
    use \App\Core\Service\Services\Deleter;
    use \App\Core\Service\Services\Detailer;
    //操作日志
    use \App\Admin\Base\LogService;
    
    protected function bootService(){
        $this->bootBaseService();
        $this->setRepository(new Repository);
        $this->setMeta(new Meta);
        $this->repository = $this->getRepository();
        //添加观察者
        $this->addListeners([
            'create' => new Listeners\CreateListener(),
            'update' => new Listeners\UpdateListener()
        ]);
    }
	
    //报修列表
    public function lists(){
        //过滤器
        $conditions = [
            new InputKeywordsCriteria('name'),
            new InputTimeRangeCriteria('created_at'),
            new InputCriteria('status')
        ];
        $count = $this->repository->addCriterias($conditions)->count();
        $conditions[] = new PaginateCriteria();
        $conditions[] = new SortCriteria('id', 'DESC');
        $data = $this->repository->resetQuery()->resetCriteria()->addCriterias($conditions)->all();
        $data->load('user','card');
        return $this->success([
            'count' => $count,
            'data' => $data
        ]);
    }

    //充值
    public function rechargecard(){
        $id = Input::get('id');
        $recharge = $this->repository->addCriteria(new FixedCriteria('id', $id))->first();
        $user_id = $recharge->user_id;
        $user = with(new UserRepository)->addCriteria(new FixedCriteria('id', $user_id))->first();
        if($recharge && $user){
            $fee = $recharge->fee;
            $enterprise_fee = $user->enterprise_fee;
            $user->enterprise_fee = $enterprise_fee+$fee;
            $user->save();

            $recharge->status = '2';
            $recharge->save();
            return $this->success();
        }
        return $this->inputError('非法操作');
    }

}